package com.zang.protobuf.client;

import com.zang.protobuf.proto.SubscribeReqProto;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author Zhang Qiang
 * @Date 2019/7/22 18:16
 */
public class SubReqClientHandler extends ChannelHandlerAdapter {


    public SubReqClientHandler(){}

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i = 0; i < 10; i++) {
            ctx.write(subReq(i));
        }
        ctx.flush();
    }

    private SubscribeReqProto.SubscribeReq subReq(int i) {
        SubscribeReqProto.SubscribeReq.Builder builder = SubscribeReqProto.SubscribeReq.newBuilder();

        builder.setSubReqId(i);
        builder.setUserName("LiLinFeng");
        builder.setProductName("Netty book for protobuf");
        String address = "";
        int a = new Random().nextInt(10);
        address = a < 6 && a > 2 ? " 北京琉璃厂 " : " 深圳红树林 ";
        address += a > 6 || a < 2 ? " 南京雨花台 " : " 西藏风火宫 ";
        builder.setAddress(address);
        return builder.build();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("Receive server response : [ " + msg + "]");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
